<script setup lang="ts">
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box';
import { useGuessList } from '@/composables';
import {
  deleteMemberCartAPI,
  getMemberCartAPI,
  putMemberCartBySkuIdAPI,
  putMemberCartSelectedAPI,
} from '@/services/cart';
import { userStore } from '@/stores';
import type { CartItem } from '@/types/cart';
import { onShow } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 是否适配底部安全区域
defineProps<{
  safeAreaInsetBottom?: boolean;
  // 是否展示返回按钮
  showBack?: boolean;
}>();
//获取Store用户信息
const userstore = userStore();
// 获取购物车列表数据
const cartList = ref<CartItem[]>([]);
const loading = ref(true);
const getMemberCartData = async () => {
  uni.showLoading({ title: '加载中...' });
  loading.value = false;
  const res = await getMemberCartAPI();
  uni.hideLoading();
  loading.value = true;
  cartList.value = res.result;
};
// 初始化调用
onShow(() => {
  // 用户已登录才允许调用
  if (userstore.profile) {
    getMemberCartData();
  }
});
// 删除购物车商品
const onDeleteCart = async (ids: string) => {
  uni.showLoading({ title: '正在加载' });
  // 后端删除接口
  await deleteMemberCartAPI({ ids: [ids] });
  uni.hideLoading();
  // 重新获取列表
  getMemberCartData();
};
// 修改商品数量
const onChangeCount = async (event: InputNumberBoxEvent) => {
  await putMemberCartBySkuIdAPI(event.index, { count: event.value });
};
// 修改商品选中状态-单个商品
const onChangeSelected = (item: CartItem) => {
  // 前端状态更新-是否选中取反
  item.selected = !item.selected;
  // 后端接口调用
  putMemberCartBySkuIdAPI(item.skuId, { selected: item.selected });
};
// 计算全选状态
const isSelectAll = computed(() => {
  return cartList.value.length && cartList.value.every((item) => item.selected);
});
// 修改商品选中状态-全选修改
const onChangeSelectedAll = async () => {
  const _isSeleectAll = !isSelectAll.value;
  // 前端状态更新
  cartList.value.forEach((item) => {
    item.selected = _isSeleectAll;
  });
  // 后端接口调用
  await putMemberCartSelectedAPI({ selected: _isSeleectAll });
};
// 计算已选商品数量
const selectedCount = computed(() => {
  return cartList.value.filter((item) => item.selected).length;
});

// 计算已选商品列表
const selectedCartList = computed(() => {
  return cartList.value.filter((item) => item.selected);
});
// 计算选中总结额
const selectedAmount = computed(() => {
  return selectedCartList.value.reduce(
    (sum, item) => sum + item.count * item.nowPrice,
    0
  );
});
// 结算
const Payment = () => {
  if (selectedCount.value === 0) {
    return uni.showToast({
      title: '请选择商品',
      icon: 'none',
    });
  }
  // 跳转到结算页
  uni.navigateTo({ url: '/pagesOrder/create-order/create-order' });
};

//返回
const back = () => {
  uni.navigateBack();
};
// 猜你喜欢组合式函数
const { guessRef, onScrolltolower } = useGuessList();
// const onScrolltolower = () => {
//   console.log('触底了');
// };
</script>

<template>
  <view
    class="custom-nav-bar"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <uni-icons
      v-if="showBack"
      class="icons"
      @tap="back"
      type="left"
      size="22"
    ></uni-icons>
    <text class="nav-title">
      <text>购物车</text>
      <text :style="{ 'font-size': '15px', color: '#333' }"
        >({{ cartList.length }})</text
      >
    </text>
  </view>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="scroll-view"
    @scrolltolower="onScrolltolower"
    v-if="loading"
  >
    <!-- 已登录: 显示购物车 -->
    <template v-if="userstore.profile">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="cartList.length">
        <!-- 优惠提示 -->
        <view class="tips">
          <text class="label">满减</text>
          <text class="desc">满1件, 即可享受9折优惠</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item
            v-for="item in cartList"
            :key="item.skuId"
            class="cart-swipe"
          >
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text
                @tap="onChangeSelected(item)"
                class="checkbox"
                :class="{ checked: item.selected }"
              ></text>
              <navigator
                :url="`/pages/goods/goods?id=${item.id}`"
                hover-class="none"
                class="navigator"
              >
                <image
                  mode="aspectFill"
                  class="picture"
                  :src="item.picture"
                ></image>
                <view class="meta">
                  <view class="name ellipsis">{{ item.name }}</view>
                  <view class="attrsText ellipsis">{{ item.attrsText }}</view>
                  <view class="price">{{ item.nowPrice }}</view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <vk-data-input-number-box
                  v-model="item.count"
                  :min="1"
                  :max="item.stock"
                  :index="item.skuId"
                  @change="onChangeCount"
                ></vk-data-input-number-box>
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button
                  class="button delete-button"
                  @tap="onDeleteCart(item.skuId)"
                >
                  <uni-icons
                    class="icons"
                    type="trash"
                    color="#fff"
                    size="20"
                  />
                  <view class="delete-text">删除</view>
                </button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="/static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator
          open-type="switchTab"
          url="/pages/index/index"
          hover-class="none"
        >
          <button class="button">去首页看看</button>
        </navigator>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <view class="guess">
      <online-guess
        :add-margin="showBack ? true : false"
        ref="guessRef"
      ></online-guess>
    </view>
    <!-- 底部占位空盒子 -->
    <view class="toolbar-height">
      <!-- 吸底工具栏 -->
      <view
        class="toolbar"
        :style="{
          paddingBottom: safeAreaInsetBottom
            ? safeAreaInsets?.bottom + 'px'
            : 0,
        }"
      >
        <text
          @tap="onChangeSelectedAll"
          class="all"
          :class="{ checked: isSelectAll }"
          >全选</text
        >
        <view class="amount-text">
          <text class="selected-count" v-show="selectedCount"
            >已选{{ selectedCount }}件，</text
          >
          <text class="text">合计:</text>
          <text class="amount">{{ selectedAmount }}</text>
        </view>
        <view class="button-grounp">
          <view @tap="Payment" class="button payment-button"> 结算 </view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss">
// 根元素
:host {
  background-color: #f7f7f8;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.custom-nav-bar {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 这将使标题靠左对齐 */
  background: linear-gradient(90deg, #ededed, #dcdcdc);
  padding: 45rpx 20rpx;
  position: fixed;
  left: 0;
  right: 0;
  z-index: 999999;
  .nav-title {
    font-size: 20px;
    position: relative;
    top: 17rpx;
    left: 20rpx;
  }
  .icons {
    position: relative;
    top: 16rpx;
  }
}
.scroll-view {
  height: 100vh;
  flex: 1;
  overflow: hidden;
}

// 购物车列表
.cart-list {
  padding: 180rpx 20rpx 0 20rpx;
  box-sizing: border-box;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #fff;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      background: linear-gradient(90deg, #ed792f, #ec602b);
      margin-right: 10rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 15rpx;
    background-color: #fff;
    position: relative;

    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e6cd';
        font-family: 'erabbit' !important;
        font-size: 40rpx;
        color: #c7c7c7;
      }

      &.checked::before {
        content: '\e6cc';
        color: #ec602b;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      // height: 72rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      width: 26vw;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      color: #444;
      margin-bottom: 2rpx;
      color: #ec602b;
      font-weight: bold;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 20rpx;
      right: 5rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 200rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
        background-color: #f6f6f6;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #e43d33;
      border-radius: 0 0 15rpx 0;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;
  .image {
    width: 400rpx;
    height: 281rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #ec602b;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 999999;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  // border-top: 1rpx solid #ededed;
  // border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;
  .all {
    margin-left: 25rpx;
    font-size: 14px;
    display: flex;
    align-items: center;
    color: #909399;
  }

  .all::before {
    font-family: 'erabbit' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
    color: #c7c7c7;
  }

  .checked::before {
    content: '\e6cc';
    color: #ec602b;
  }
  .selected-count {
    font-size: 13px;
    color: #888;
    margin-right: -8rpx;
  }
  .amount-text {
    position: absolute;
    right: 250rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .text {
    margin-right: 8rpx;
    right: 20rpx;
    color: #444;
    font-size: 13px;
  }

  .amount {
    font-size: 20px;
    color: #ec602b;
    font-weight: bold;

    .decimal {
      font-size: 12px;
    }

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 16px;
    color: #fff;

    .button {
      width: 200rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background: linear-gradient(90deg, #ed792f, #ec602b);

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
// 底部占位空盒子
.toolbar-height {
  height: 100rpx;
}
</style>
